import { mutation } from "./_generated/server";
import { v } from "convex/values";

const images = [
  "/placeholders/1.jpg",
  "/placeholders/2.jpg",
  "/placeholders/3.jpg",
  "/placeholders/4.jpg",
  "/placeholders/5.jpg",
  "/placeholders/6.jpg",
  "/placeholders/7.jpg",
  "/placeholders/8.jpg",
  "/placeholders/9.jpg",
];

// https://docs.convex.dev/functions/mutation-functions
// mutation 用于处理数据库的修改操作
// 创建会员
export const create = mutation({
  args: {
    // mutation 所接受的参数
    orgId: v.string(),
    title: v.string(),
  },
  handler: async (ctx, args) => {
    // ctx上下文对象，包含与当前请求相关的各种信息和功能，比如数据库访问、身份验证等
    // args调用 mutation 时传入的参数对象，这里会包含 orgId 和 title
    const identity = await ctx.auth.getUserIdentity(); // 获取当前用户的身份信息
    if (!identity) {
      throw new Error("Unauthorized");
    }

    const randomImage = images[Math.floor(Math.random() * images.length)];

    const board = await ctx.db.insert("boards", {
      title: args.title,
      orgId: args.orgId,
      authorId: identity.subject,
      authorName: identity.name as string,
      imageUrl: randomImage,
    });

    return board;
  },
});

// 移除
export const remove = mutation({
  args: {
    // mutation 所接受的参数
    id: v.id("boards"), // 验证数据是否为指定集合中的有效 ID
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity(); // 获取当前用户的身份信息

    if (!identity) throw new Error("未知错误");

    // TODO:删除与收藏的关系

    await ctx.db.delete(args.id);
  },
});

// 更新
export const update = mutation({
  args: {
    id: v.id("boards"),
    title: v.string(),
  },
  handler: async (ctx, args) => {
    const identity = ctx.auth.getUserIdentity();

    if (!identity) throw new Error("未知错误");

    const title = args.title.trim();

    if (!title) throw new Error("title必传");

    if (title.length > 60) throw new Error("title长度不可超过60");

    const board = await ctx.db.patch(args.id, {
      title: args.title,
    });

    return board;
  },
});
